<template>
  <div>
    <a-card :bordered="false" v-show="!hiddenSearch">
      <a-row>
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="5" :sm="12">
                <a-form-item label="用户名">
                  <a-input v-model="queryParam.userName" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="12">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.status" placeholder="请选择" default-value="">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="true">启用</a-select-option>
                    <a-select-option value="false">锁定</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="12">
                <a-form-item label="性别">
                  <a-select v-model="queryParam.sex" placeholder="请选择" default-value="">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="0">男</a-select-option>
                    <a-select-option value="1">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="3" :sm="12">
                <span class="table-page-search-submitButtons" >
                  <a-tooltip placement="topLeft" title="查询" arrow-point-at-center>
                    <a-button shape="circle" @click="$refs.table.refresh(true)" icon="search"/>
                  </a-tooltip>
                  <a-tooltip placement="topLeft" title="重置" arrow-point-at-center>
                    <a-button style="margin-left: 8px" @click="() => this.queryParam = {}" icon="sync"/>
                  </a-tooltip>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-row>
    </a-card>
    <a-card
      style="margin-top: 10px"
      :bordered="false">
      <div class="table-operator">
        <a-tooltip placement="topLeft" title="隐藏/显示搜索栏" arrow-point-at-center>
          <a-button size="small" style="position: absolute;right: 55px;top: 25px;" shape="circle" :icon="icon" @click="hiddenSearchMenu(hiddenSearch)"/>
        </a-tooltip>
        <a-button v-show="addEnable" type="primary" shape="round" icon="plus-circle" @click="$refs.modal.add()">添加</a-button>
        <a-button v-show="delEnable && selectedRowKeys.length > 0" shape="round" type="danger" icon="delete" @click="onClick(selectedRowKeys)">删除</a-button>
        <!--<a-button v-show="exportEnable" type="primary" shape="round" icon="export" @click="$refs.user_export.export(queryParam)">导出</a-button>-->
      </div>
      <a-row :gutter="10">
        <a-col :span="5">
          <div>
            <a-input style="margin-bottom: 8px" :placeholder="holderText" v-model="searchValue" @change="handleChange" ref="searchInput" >
              <a-icon slot="prefix" type="search" />
              <a-icon v-if="searchValue" slot="suffix" type="close-circle" @click="emitEmpty" />
            </a-input>
            <a-tree
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="orgTree"
              @expand="onExpand"
              @select="handleSelect"
            >
              <template slot="title" slot-scope="{ title }">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{ title.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ title }}</span>
              </template>
            </a-tree>
          </div>
        </a-col>
        <a-col :span="19">
          <s-table
            ref="table"
            row-key="id"
            size="middle"
            :columns="columns"
            :data="loadData"
            :showTotal="true"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          >
            <span slot="customUserNameTitle"><a-icon type="user" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  用户名</span>
            <span slot="customStatusTitle"><a-icon type="lock" theme="twoTone"/>  状态</span>
            <span slot="customHeadPortraitTitle"><a-icon type="picture" theme="twoTone"/>  头像</span>
            <span slot="customSexTitle"><a-icon type="man" :style="{ fontSize: '16px', color: '#4F99FF' }"/>|<a-icon type="woman" :style="{ fontSize: '16px', color: '#eb2f96' }"/>性别</span>
            <span slot="customLoginNameTitle"><a-icon type="user" theme="twoTone"/>  账户名</span>
            <span slot="customCreateTimeTitle"><a-icon type="clock-circle" theme="twoTone"/>  创建时间</span>
            <span slot="customActionTitle"><a-icon type="form" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  操作</span>
            <img
              slot="headPortrait"
              style="width:30px;height:30px;cursor:pointer;"
              slot-scope="text"
              :src="text"
              :onerror="defaultImag"
              @click="handlePreview(text)"/>
            <span slot="status" slot-scope="text, record">
              <a-switch :disabled="!editEnable || record.id === '1'" :checked="text" @change="changeStatus(record,!text)">
                <a-icon slot="checkedChildren" type="unlock" />
                <a-icon slot="unCheckedChildren" type="lock" />
              </a-switch>
            </span>
            <span slot="sex" slot-scope="sex">
              <a-tag
                :key="sex"
                :color="sex === '0' ? 'blue' : 'red'"
              >
                {{ sex === '0'? '男': sex === '1' ? '女' : '未知' }}
              </a-tag>
            </span>
            <span slot="action" slot-scope="text, record">
              <template>
                <a-dropdown :trigger="['click']">
                  <a-menu slot="overlay" v-if="editEnable || delEnable || resetPasswordEnable">
                    <a-menu-item v-show="editEnable"><a @click="handleEdit(record)"><a-icon type="edit" theme="filled"/> 编辑</a></a-menu-item>
                    <a-menu-item v-show="delEnable"><a @click="onClick([record.id])"><a-icon type="delete" theme="filled"/> 删除</a></a-menu-item>
                    <a-menu-item v-show="resetPasswordEnable"><a @click="resetPassWord(record)"><a-icon type="unlock" theme="filled"/> 重置密码</a></a-menu-item>
                  </a-menu>
                  <a> <a-button type="dashed" icon="bars"/></a>
                </a-dropdown>
              </template>
            </span>
          </s-table>
        </a-col>
      </a-row>
      <user-reset-pwd-modal ref="pwdmodal"/>
      <user-modal ref="modal" @ok="handleOk"/>
      <user-export-modal ref="user_export"/>
      <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
        <img style="width: 100%" :src="previewImage" :onerror="defaultImag"/>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { STable, SearchTree } from '@/components'
import { findDeptList, getUserList, changeStatus, delUser } from '@/api/system'
import { checkPermission } from '@/utils/permissions'
import message from 'ant-design-vue/es/message'
import UserResetPwdModal from '../modules/UserResetPwdModal'
import UserModal from '../modules/UserModal'
import UserExportModal from '../modules/UserExportModal'
import Info from '../../list/components/Info'

const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
export default {
  name: 'UserList',
  components: {
    STable,
    SearchTree,
    UserResetPwdModal,
    UserModal,
    UserExportModal,
    Info
  },
  data () {
    return {
      defaultImag: 'this.src="' + require('../../../assets/user/user_default.jpeg') + '"',
      previewImage: null,
      previewVisible: false,
      dataList: [],
      holderText: '搜索部门',
      editEnable: checkPermission('system:user:edit'),
      delEnable: checkPermission('system:user:remove'),
      resetPasswordEnable: checkPermission('system:user:resetPwd'),
      addEnable: checkPermission('system:user:add'),
      exportEnable: checkPermission('system:user:export'),

      // 查询参数
      queryParam: {},
      searchValue: '',
      autoExpandParent: true,
      hiddenSearch: false,
      icon: 'eye-invisible',
      // 表头
      columns: [
        {
          align: 'center',
          dataIndex: 'userName',
          slots: { title: 'customUserNameTitle' }
        },
        {
          align: 'center',
          dataIndex: 'headPortrait',
          scopedSlots: { customRender: 'headPortrait' },
          slots: { title: 'customHeadPortraitTitle' }
        },
        {
          dataIndex: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' },
          slots: { title: 'customStatusTitle' }
        },
        {
          align: 'center',
          dataIndex: 'sex',
          scopedSlots: { customRender: 'sex' },
          slots: { title: 'customSexTitle' }
        },
        {
          align: 'center',
          dataIndex: 'loginName',
          slots: { title: 'customLoginNameTitle' }
        },
        {
          align: 'center',
          dataIndex: 'createTime',
          slots: { title: 'customCreateTimeTitle' },
          sorter: true
        },
        {
          dataIndex: 'action',
          width: '100px',
          scopedSlots: { customRender: 'action' },
          slots: { title: 'customActionTitle' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getUserList(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      orgTree: [],
      selectedRowKeys: [],
      selectedRows: [],
      expandedKeys: []
    }
  },
  created () {
    this.findAllDeptTree()
  },
  methods: {
    previewCancel () {
      this.previewVisible = false
    },
    handlePreview (url) {
      this.previewImage = url
      this.previewVisible = true
    },
    hiddenSearchMenu (hiddenSearch) {
      this.hiddenSearch = hiddenSearch !== true
      this.icon = this.hiddenSearch === true ? 'eye' : 'eye-invisible'
    },
    handleEdit (record) {
      this.$refs.modal.edit(record)
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    resetPassWord (record) {
      this.$refs.pwdmodal.edit(record)
    },
    onClick (ids) {
      const self = this
      this.$confirm({
        title: '你确定删除该用户吗?',
        content: <div style="color:red;">用户删除将永久不能恢复</div>,
        onOk () {
          delUser(ids).then(() => {
            self.$refs.table.refresh()
            message.success('删除用户成功')
            self.selectedRowKeys = []
          }).catch(res => {
            message.error(((res.response || {}).data || {}).message || res.message)
          })
        },
        onCancel () {
          self.selectedRowKeys = []
        }
      })
    },
    async changeStatus (record, checked) {
      await changeStatus({ id: record.id, status: checked }).then(res => {
        this.$refs.table.refresh()
        if (checked) {
          message.success('解锁成功')
        } else {
          message.success('锁定成功')
        }
      })
    },
    handleChange () {
      this.onChange()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    findAllDeptTree () {
      findDeptList(Object.assign(this.queryParam)).then(res => {
        const data = res.data
        if (data.length > 0) {
          const min = Math.min(...data.map(m => m.parentId))
          this.buildTree(data, this.orgTree, String(min))
          const expandedKeySet = new Set(data.map(m => m.parentId))
          this.expandedKeys = Array.from(expandedKeySet)
          this.dataList = data.map(m => {
            return { key: m.id, title: m.deptName }
          })
        }
      })
    },
    buildTree (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.id,
            value: item.id, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildTree(list, child.children, item.id)
          if (child.children.length === 0) { delete child.children }
          arr.push(child)
        }
      })
    },
    emitEmpty () {
      this.$refs.searchInput.focus()
      this.searchValue = ''
      this.onChange()
    },
    handleSelect (selectedKeys, info) {
      this.queryParam = {
        deptId: selectedKeys[0]
      }
      this.$refs.table.refresh(true)
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange (e) {
      const value = this.searchValue
      const expandedKeys = this.dataList.map(item => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.orgTree)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    }
  }
}
</script>

<style lang="less">
  .custom-tree {
  /deep/ .ant-menu-item-group-title {
    position: relative;
  &:hover {
  .btn {
    display: block;
  }
  }
  }

  /deep/ .ant-menu-item {
  &:hover {
  .btn {
    display: block;
  }
  }
  }

  /deep/ .btn {
    display: none;
    position: absolute;
    top: 0;
    right: 10px;
    width: 20px;
    height: 40px;
    line-height: 40px;
    z-index: 1050;

  &:hover {
     transform: scale(1.2);
     transition: 0.5s all;
   }
  }
  }
</style>
